<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天室 - 用户列表</title>
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
</head>
<body>
    <div class="container">
        <header class="header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; padding: 20px 0; border-bottom: 1px solid #eee;">
            <div class="user-info" style="display: flex; align-items: center;">
                <div id="current-user-avatar" class="user-avatar"></div>
                <h2 id="current-username" style="margin-left: 15px;"></h2>
            </div>
            <div>
                <button id="create-group-btn" class="btn" style="margin-right: 10px;"><i class="fas fa-users"></i> 创建群聊</button>
                <button id="join-group-btn" class="btn btn-secondary"><i class="fas fa-sign-in-alt"></i> 加入群聊</button>
                <button id="logout-btn" class="btn" style="background-color: #f44336; margin-left: 10px;"><i class="fas fa-sign-out-alt"></i> 退出</button>
            </div>
        </header>
        
        <div class="tabs" style="margin-bottom: 20px;">
            <button id="friends-tab" class="tab-btn active" style="background: none; border: none; padding: 10px 20px; font-size: 16px; cursor: pointer; border-bottom: 2px solid var(--primary-color);">好友</button>
            <button id="groups-tab" class="tab-btn" style="background: none; border: none; padding: 10px 20px; font-size: 16px; cursor: pointer;">群聊</button>
        </div>
        
        <div class="search-container" style="margin-bottom: 20px;">
            <input type="text" id="search-input" class="form-control" placeholder="搜索用户名..." style="width: 300px;">
            <button id="search-btn" class="btn" style="margin-left: 10px;"><i class="fas fa-search"></i> 搜索</button>
        </div>
        
        <div id="friends-container">
            <h3>我的好友</h3>
            <div id="friends-list" class="user-list"></div>
        </div>
        
        <div id="groups-container" style="display: none;">
            <h3>我的群聊</h3>
            <div id="groups-list" class="user-list"></div>
        </div>
        
        <div id="search-results-container" style="display: none; margin-top: 30px;">
            <h3>搜索结果</h3>
            <div id="search-results" class="user-list"></div>
        </div>
    </div>
    
    <!-- 创建群聊模态框 -->
    <div id="create-group-modal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 100; justify-content: center; align-items: center;">
        <div class="modal-content" style="background-color: white; padding: 30px; border-radius: var(--border-radius); width: 400px;">
            <h3 style="margin-bottom: 20px;">创建新群聊</h3>
            <div class="form-group">
                <input type="text" id="group-name" class="form-control" placeholder="群聊名称" required>
            </div>
            <div style="display: flex; justify-content: flex-end;">
                <button id="cancel-create-group" class="btn" style="background-color: #ccc; margin-right: 10px;">取消</button>
                <button id="confirm-create-group" class="btn">创建</button>
            </div>
        </div>
    </div>
    
    <!-- 加入群聊模态框 -->
    <div id="join-group-modal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 100; justify-content: center; align-items: center;">
        <div class="modal-content" style="background-color: white; padding: 30px; border-radius: var(--border-radius); width: 400px;">
            <h3 style="margin-bottom: 20px;">加入群聊</h3>
            <div class="form-group">
                <input type="text" id="room-code" class="form-control" placeholder="群聊房间号" required>
            </div>
            <div style="display: flex; justify-content: flex-end;">
                <button id="cancel-join-group" class="btn" style="background-color: #ccc; margin-right: 10px;">取消</button>
                <button id="confirm-join-group" class="btn">加入</button>
            </div>
        </div>
    </div>
    
    <script>
        // 检查用户是否已登录
        const currentUser = JSON.parse(localStorage.getItem('user'));
        console.log('当前用户信息:', currentUser);
        
        if (!currentUser || !currentUser.id) {
            console.error('用户信息不完整，重定向到登录页面');
            localStorage.removeItem('user'); // 清除不完整的用户数据
            window.location.href = '/login';
        }
        
        // 显示当前用户信息
        document.getElementById('current-username').textContent = currentUser.username;
        const userAvatar = document.getElementById('current-user-avatar');
        userAvatar.textContent = currentUser.username.charAt(0).toUpperCase();
        
        // 获取好友列表
        function loadFriends() {
            fetch(`/api/users/${currentUser.id}/friends`)
                .then(response => response.json())
                .then(friends => {
                    const friendsList = document.getElementById('friends-list');
                    friendsList.innerHTML = '';
                    
                    if (friends.length === 0) {
                        friendsList.innerHTML = '<p>暂无好友，请通过搜索添加好友</p>';
                        return;
                    }
                    
                    friends.forEach(friend => {
                        const friendCard = document.createElement('div');
                        friendCard.className = 'card user-card';
                        friendCard.innerHTML = `
                            <div class="user-avatar">${friend.username.charAt(0).toUpperCase()}</div>
                            <div class="user-info">
                                <div class="user-name">${friend.username}</div>
                            </div>
                        `;
                        
                        // 双击进入聊天页面
                        friendCard.addEventListener('dblclick', () => {
                            window.location.href = `/chat?type=private&userId=${friend.id}`;
                        });
                        
                        friendsList.appendChild(friendCard);
                    });
                })
                .catch(error => console.error('加载好友列表失败:', error));
        }
        
        // 获取群聊列表
        function loadGroups() {
            fetch(`/api/users/${currentUser.id}/chatrooms`)
                .then(response => response.json())
                .then(groups => {
                    const groupsList = document.getElementById('groups-list');
                    groupsList.innerHTML = '';
                    
                    if (groups.length === 0) {
                        groupsList.innerHTML = '<p>暂无群聊，请创建或加入群聊</p>';
                        return;
                    }
                    
                    groups.forEach(group => {
                        const groupCard = document.createElement('div');
                        groupCard.className = 'card user-card';
                        groupCard.innerHTML = `
                            <div class="user-avatar" style="background-color: #FF9800;">${group.name.charAt(0).toUpperCase()}</div>
                            <div class="user-info">
                                <div class="user-name">${group.name}</div>
                                <div style="font-size: 12px; color: #666;">房间号: ${group.roomCode}</div>
                            </div>
                        `;
                        
                        // 双击进入聊天页面
                        groupCard.addEventListener('dblclick', () => {
                            window.location.href = `/chat?type=group&roomCode=${group.roomCode}`;
                        });
                        
                        groupsList.appendChild(groupCard);
                    });
                })
                .catch(error => console.error('加载群聊列表失败:', error));
        }
        
        // 搜索用户
        document.getElementById('search-btn').addEventListener('click', () => {
            const query = document.getElementById('search-input').value.trim();
            if (!query) return;
            
            fetch(`/api/users/search?query=${encodeURIComponent(query)}`)
                .then(response => response.json())
                .then(users => {
                    const searchResults = document.getElementById('search-results');
                    searchResults.innerHTML = '';
                    document.getElementById('search-results-container').style.display = 'block';
                    
                    if (users.length === 0) {
                        searchResults.innerHTML = '<p>没有找到匹配的用户</p>';
                        return;
                    }
                    
                    users.forEach(user => {
                        // 排除当前用户
                        if (user.id === currentUser.id) return;
                        
                        const userCard = document.createElement('div');
                        userCard.className = 'card user-card';
                        userCard.innerHTML = `
                            <div class="user-avatar">${user.username.charAt(0).toUpperCase()}</div>
                            <div class="user-info">
                                <div class="user-name">${user.username}</div>
                            </div>
                            <button class="btn add-friend-btn" data-id="${user.id}">添加好友</button>
                        `;
                        
                        searchResults.appendChild(userCard);
                    });
                    
                    // 添加好友事件
                    document.querySelectorAll('.add-friend-btn').forEach(btn => {
                        btn.addEventListener('click', () => {
                            const friendId = btn.getAttribute('data-id');
                            fetch(`/api/users/${currentUser.id}/friends/${friendId}`, {
                                method: 'POST'
                            })
                            .then(response => {
                                if (response.ok) {
                                    alert('添加好友成功');
                                    loadFriends();
                                } else {
                                    alert('添加好友失败');
                                }
                            })
                            .catch(error => console.error('添加好友失败:', error));
                        });
                    });
                })
                .catch(error => console.error('搜索用户失败:', error));
        });
        
        // 切换标签页
        document.getElementById('friends-tab').addEventListener('click', () => {
            document.getElementById('friends-tab').classList.add('active');
            document.getElementById('groups-tab').classList.remove('active');
            document.getElementById('friends-container').style.display = 'block';
            document.getElementById('groups-container').style.display = 'none';
            
            // 更新边框样式
            document.getElementById('friends-tab').style.borderBottom = '2px solid var(--primary-color)';
            document.getElementById('groups-tab').style.borderBottom = 'none';
        });
        
        document.getElementById('groups-tab').addEventListener('click', () => {
            document.getElementById('groups-tab').classList.add('active');
            document.getElementById('friends-tab').classList.remove('active');
            document.getElementById('groups-container').style.display = 'block';
            document.getElementById('friends-container').style.display = 'none';
            
            // 更新边框样式
            document.getElementById('groups-tab').style.borderBottom = '2px solid var(--primary-color)';
            document.getElementById('friends-tab').style.borderBottom = 'none';
        });
        
        // 创建群聊
        document.getElementById('create-group-btn').addEventListener('click', () => {
            document.getElementById('create-group-modal').style.display = 'flex';
        });
        
        document.getElementById('cancel-create-group').addEventListener('click', () => {
            document.getElementById('create-group-modal').style.display = 'none';
        });
        
        document.getElementById('confirm-create-group').addEventListener('click', () => {
            const groupName = document.getElementById('group-name').value.trim();
            if (!groupName) return;
            
            fetch('/api/chatrooms', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: groupName,
                    creatorUsername: currentUser.username
                })
            })
            .then(response => {
                if (response.ok) {
                    alert('创建群聊成功');
                    document.getElementById('create-group-modal').style.display = 'none';
                    loadGroups();
                } else {
                    alert('创建群聊失败');
                }
            })
            .catch(error => console.error('创建群聊失败:', error));
        });
        
        // 加入群聊
        document.getElementById('join-group-btn').addEventListener('click', () => {
            document.getElementById('join-group-modal').style.display = 'flex';
        });
        
        document.getElementById('cancel-join-group').addEventListener('click', () => {
            document.getElementById('join-group-modal').style.display = 'none';
        });
        
        document.getElementById('confirm-join-group').addEventListener('click', () => {
            const roomCode = document.getElementById('room-code').value.trim();
            if (!roomCode) return;
            
            fetch(`/api/chatrooms/${roomCode}/join`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: currentUser.username
                })
            })
            .then(response => {
                if (response.ok) {
                    alert('加入群聊成功');
                    document.getElementById('join-group-modal').style.display = 'none';
                    loadGroups();
                } else {
                    alert('加入群聊失败，请检查房间号是否正确');
                }
            })
            .catch(error => console.error('加入群聊失败:', error));
        });
        
        // 退出登录
        document.getElementById('logout-btn').addEventListener('click', () => {
            localStorage.removeItem('user');
            window.location.href = '/login';
        });
        
        // 初始加载
        loadFriends();
        loadGroups();
    </script>
</body>
</html> 